<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { onMounted } from "vue";
import {
  deleteproductStorageApi,
  executeInStorageApi,
  executeOutStorageApi,
  getproductStorageListApi,
} from "@/api/productStorage";
import { ElMessage, ElMessageBox } from "element-plus";
import { productStorageResultsData } from "@/api/productStorage/res";
import {
  ProductStorageSearchType,
  PaginationType,
} from "@/api/productStorage/params";

let queryParams = ref({
  storageCode: "", // 入库单号/名称
  batchNumber: "", // 批次号
  status: "", // 状态
  storageDate: "", // 入库时间
  workOrderCode: "", // 工单单号/名称
});
let loading = ref(false);
// mockData
let sourceData = ref(["销售订单", "库存备货", "其他"]);
let stateData = ref(["未分解", "已分解", "已完成", "已关闭", "已撤回"]);
let tableData = ref<productStorageResultsData[]>([
  {
    objectId: "",
    productlistId: "",
    storageName: "",
    storageCode: "",
    storageDate: "",
    workOrderName: "",
    workOrderCode: "",
    productName: "",
    productCode: "",
    specification: "",
    unit: "",
    batchNumber: "",
    quantity: "",
    warehouseName: "",
    areaName: "",
    locationName: "",
    status: "",
    createdAt: "",
    updatedAt: "",
  },
]);

let params = ref<PaginationType>({
  currentPage: 1,
  pageSize: 10,
});
let ifSearch = ref(false);
let total = ref(0);
let showDatePicker = ref(false);
const $router = useRouter();
const filteredSearchData: Partial<ProductStorageSearchType> = {};

const handler = (page) => {
  params.value.currentPage = page;
  if (ifSearch.value) {
    getTableData(filteredSearchData);
  } else {
    getTableData();
  }
};
const sizeHandler = (page_size) => {
  params.value.pageSize = page_size;
  if (ifSearch.value) {
    getTableData(filteredSearchData);
  } else {
    getTableData();
  }
};
const gotoAdd = () => {
  $router.push("/storage/entrance/addProduct");
};

const updateProduct = (row) => {
  $router.push({
    path: "/storage/entrance/updateProduct",
    query: {
      objectId: row.objectId,
    },
  });
};

const gotoDetail = (row) => {
  $router.push({
    path: "/storage/entrance/productDetail",
    query: {
      objectId: row.objectId,
    },
  });
};
const handleInStorage = async (row) => {
  try {
    // 确认入库操作
    await ElMessageBox.confirm(
      `确定要将生产单 "${row.storageName}" 入库吗？`,
      "确认",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    // 执行出库操作
    await executeInStorageApi(row.objectId);

    ElMessage({
      message: "修改入库操作成功",
      type: "success",
    });

    // 刷新列表
    getTableData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("修改入库操作失败:", error);
      ElMessage.error("修改入库操作失败");
    }
  }
};

const handleOutStorage = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要将生产单 "${row.storageName}" 撤回吗？`,
      "确认",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    await executeOutStorageApi(row.objectId);

    ElMessage({
      message: "撤回入库操作成功",
      type: "success",
    });

    getTableData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("撤回入库操作失败:", error);
      ElMessage.error("撤回入库操作失败");
    }
  }
};

const getTableData = async (data?) => {
  try {
    loading.value = true;
    const TotalRes = await getproductStorageListApi();
    total.value = TotalRes.results.length;
    const res = await getproductStorageListApi(data, params.value);
    tableData.value = res.results;
    if (ifSearch.value) {
      total.value = res.results.length;
    }
    console.log(tableData.value);
  } catch (err: any) {
    console.log(err);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

const resetQuery = () => {
  queryParams.value = {
    storageCode: "",
    batchNumber: "",
    status: "",
    storageDate: "",
    workOrderCode: "",
  };
  params.value.currentPage = 1;
  params.value.pageSize = 10;
  ifSearch.value = false;
  getTableData();
};

//删除
const deleteData = async (objectId: string) => {
  try {
    await deleteproductStorageApi(objectId);
    getTableData();
    ElMessage.success("删除成功");
  } catch (err: any) {
    console.log(err);
    ElMessage.error("删除失败");
  }
};

const onSearch = () => {
  let allFieldsEmpty = true;
  Object.keys(filteredSearchData).forEach((key) => {
    delete filteredSearchData[key];
  });
  for (const key in queryParams.value) {
    if (queryParams.value[key] !== "" && queryParams.value[key] !== null) {
      allFieldsEmpty = false;
      filteredSearchData[key] = queryParams.value[key];
    }
  }
  ifSearch.value = !allFieldsEmpty;
  params.value.currentPage = 1;
  params.value.pageSize = 10;
  getTableData(filteredSearchData);
};

//更新编辑

onMounted(() => {
  getTableData();
});
</script>

<template>
  <div style="padding: 20px">
    <el-card>
      <div class="operateContainer">
        <div
          class="formContainer"
          :style="showDatePicker ? 'height:85px' : 'height:32px'"
        >
          <el-form inline :model="queryParams">
            <el-form-item>
              <el-input
                v-model="queryParams.storageCode"
                placeholder="请输入入库单号/名称"
                style="width: 250px"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="queryParams.batchNumber"
                placeholder="请输入批次号"
                style="width: 250px"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="queryParams.status"
                placeholder="请选择状态"
                style="width: 180px"
              >
                <el-option
                  v-for="item in stateData"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <div style="margin-top: 20px">
              <el-form-item>
                <el-date-picker
                  v-model="queryParams.storageDate"
                  style="width: 250px"
                  type="date"
                  placeholder="请选择入库时间"
                ></el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="queryParams.workOrderCode"
                  placeholder="请输入工单单号/名称"
                  style="width: 250px"
                ></el-input>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="searchOperate">
          <div class="button">
            <el-button
              type="primary"
              @click="resetQuery"
              plain
              style="width: 80px"
              >重置</el-button
            >
            <el-button type="primary" @click="onSearch" style="width: 80px"
              >查询</el-button
            >
          </div>
          <div class="more">
            <el-button
              type="primary"
              link
              @click="showDatePicker = !showDatePicker"
              >更多</el-button
            >
            <el-icon color="#1B9AEE" :class="{ 'rotate-180': showDatePicker }">
              <CaretBottom />
            </el-icon>
          </div>
        </div>
      </div>
    </el-card>
    <el-card style="margin-top: 20px">
      <template #header>
        <span style="font-weight: bold">产品入库</span>
      </template>
      <div class="operate">
        <el-button style="width: 80px" type="primary" @click="gotoAdd"
          >新增</el-button
        >
        <el-button style="width: 80px" type="primary" plain>导出</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="margin-top: 15px"
        border
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="60"
          fixed="left"
        ></el-table-column>
        <el-table-column
          align="center"
          label="入库单名称"
          fixed="left"
          width="100"
          prop="storageName"
        >
          <template #="{ row, $index }">
            <el-button link type="primary" @click="gotoDetail(row)">{{
              row.storageName
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="入库单编号"
          fixed="left"
          width="110"
          prop="storageCode"
        ></el-table-column>
        <el-table-column
          align="center"
          label="入库日期"
          width="100"
          prop="storageDate"
        ></el-table-column>
        <el-table-column
          align="center"
          label="工单名称"
          width="90"
          prop="workOrderName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="工单编号"
          width="100"
          prop="workOrderCode"
        ></el-table-column>
        <el-table-column
          align="center"
          label="产品名称"
          width="90"
          prop="productName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="产品编号"
          width="100"
          prop="productCode"
        ></el-table-column>
        <el-table-column
          align="center"
          label="规格型号"
          width="90"
          prop="specification"
        ></el-table-column>
        <el-table-column
          align="center"
          label="单位"
          width="90"
          prop="unit"
        ></el-table-column>
        <el-table-column
          align="center"
          label="批次号"
          width="90"
          prop="batchNumber"
        ></el-table-column>
        <el-table-column
          align="center"
          label="入库数量"
          width="90"
          prop="quantity"
        ></el-table-column>
        <el-table-column
          align="center"
          label="仓库名称"
          width="90"
          prop="warehouseName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="库区名称"
          width="90"
          prop="areaName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="库位名称"
          width="90"
          prop="locationName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="状态"
          width="150"
          prop="status"
          fixed="right"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleInStorage(row)"
              v-if="row.status === '未入库'"
              >入库</el-button
            >
            <el-button
              link
              type="primary"
              @click="updateProduct(row)"
              v-if="row.status === '未入库'"
              >编辑</el-button
            >
            <el-button
              link
              type="primary"
              @click="deleteData(row.objectId)"
              v-if="row.status === '未入库'"
              >删除</el-button
            >

            <el-button
              link
              type="primary"
              @click="handleOutStorage(row)"
              v-if="row.status === '已入库'"
              >撤回</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="params.currentPage"
        v-model:page-size="params.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout="prev,pager,next,jumper,->,sizes,total"
        :total="total"
        @current-change="handler"
        @size-change="sizeHandler"
        style="margin-top: 10px"
      ></el-pagination>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.operateContainer {
  display: flex;
  align-content: center;
  justify-content: space-between;
  .formContainer {
    width: 1060px;
    height: 32px;
    transition: height 0.3s ease; // 添加高度变化的过渡效果
    overflow: hidden; // 防止内容溢出
    .el-form-item {
      margin-bottom: 0;
    }
  }
  .searchOperate {
    display: flex;
    align-items: center;
    .more {
      margin-left: 20px;
      display: flex;
      align-items: center;
    }
  }
}

/* 定义旋转动画 */
.rotate-180 {
  transition: transform 0.3s ease;
  transform: rotate(180deg);
}
</style>
